//
//  DKTextField.m
//  DKTextField
//
//  Created by 张奥 on 14-10-31.
//  Copyright (c) 2014年 DKHS. All rights reserved.
//http://www.jianshu.com/p/ff68151fe83b

#import "HLTextField.h"


@interface HLTextField ()
@property (nonatomic, copy) NSString *password;
@property (nonatomic, weak) id beginEditingObserver;
@property (nonatomic, weak) id endEditingObserver;
//是否为密码输入框
@property (nonatomic, assign) BOOL isPW;
@end

@implementation HLTextField


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return self;
}



- (instancetype)initWithIsPW:(BOOL)isPassWord
{
    self = [super init];
    if (self) {
        if(isPassWord)
        {
            self.password = @"";
            
            __weak HLTextField *weakSelf = self;
            
            self.beginEditingObserver = [[NSNotificationCenter defaultCenter]
                                         addObserverForName:UITextFieldTextDidBeginEditingNotification
                                         object:nil
                                         queue:nil
                                         usingBlock:^(NSNotification *note) {
                                             if (weakSelf == note.object && weakSelf.isSecureTextEntry) {
                                                 weakSelf.text = @"";
                                                 [weakSelf insertText:weakSelf.password];
                                             }
                                         }];
            
            self.endEditingObserver = [[NSNotificationCenter defaultCenter]
                                       addObserverForName:UITextFieldTextDidEndEditingNotification
                                       object:nil
                                       queue:nil
                                       usingBlock:^(NSNotification *note) {
                                           if (weakSelf == note.object) {
                                               weakSelf.password = weakSelf.text;
                                           }
                                       }];
        }
    }
    return self;
}


- (void)textFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    toBeString = [self filterCharactor:textField.text withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
    NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage;//[[UITextInputMode currentInputMode] primaryLanguage];
    if([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if(!position) {
            textField.text = [self lengthLimit:toBeString];
        }
        else{
        }
    }
    else{
        textField.text = [self lengthLimit:toBeString];
    }
}

- (NSString *)lengthLimit:(NSString *)toBeString {
    switch (self.textFieldType) {
        case MCTextFieldIdCard:
        {
            if(toBeString.length > 18) {
                return [toBeString substringToIndex:18];
            }
        }
            break;
        case MCTextFieldPhone: {
            if(toBeString.length > 11) {
                return [toBeString substringToIndex:11];
            }
        }
            break;
        case MCTextFieldPWD: {
            if(toBeString.length > 20) {
                return [toBeString substringToIndex:20];
            }
        }
            break;
        case MCTextFieldCode: {
            if(toBeString.length > 6) {
                return [toBeString substringToIndex:6];
            }
        }
            break;
        case MCTextFieldSQL: {
            if(toBeString.length > 50) {
                return [toBeString substringToIndex:50];
            }
        }
        
        default:
        {
            return toBeString;
        }
            break;
    }
    return toBeString;
}

- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *filterText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:filterText options:NSMatchingReportCompletion range:NSMakeRange(0, filterText.length) withTemplate:@""];
    return result;
}

- (void)setSecureTextEntry:(BOOL)secureTextEntry {
    BOOL isFirstResponder = self.isFirstResponder;
    [self resignFirstResponder];
    [super setSecureTextEntry:secureTextEntry];
    if (isFirstResponder) {
        [self becomeFirstResponder];
    }
}


//控制输入后文本的位置，缩进
- (CGRect)editingRectForBounds:(CGRect)bounds {
    if (UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, self.textInsets)) {
        return [super editingRectForBounds:bounds];
    }
    return UIEdgeInsetsInsetRect(bounds, self.textInsets);
}
//控制还未输入时文本的位置，缩进
- (CGRect)textRectForBounds:(CGRect)bounds {
    if (UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, self.textInsets)) {
        return [super textRectForBounds:bounds];
    }
    return UIEdgeInsetsInsetRect(bounds, self.textInsets);
}

//控制提示文字的位置，缩进
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    if (UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, self.placeholderInsets)) {
        return [super placeholderRectForBounds:bounds];
    }
    return UIEdgeInsetsInsetRect(bounds, self.placeholderInsets);
}



/*

 
 
 
 
 在两个方法中我们分别返回编辑的区域和文本显示的区域，通过重写这两个方法很好的满足了产品设计的要求。当然UITextField还有其它的一些方法。如
 - (CGRect)borderRectForBounds:(CGRect)bounds;      指定矩形边界
 - (CGRect)textRectForBounds:(CGRect)bounds;        指定显示文本的边界
 - (CGRect)placeholderRectForBounds:(CGRect)bounds; 指定占位符的边界
 - (CGRect)editingRectForBounds:(CGRect)bounds;     指定编辑中文本的边界
 - (CGRect)clearButtonRectForBounds:(CGRect)bounds; 指定显示清除按钮的边界
 - (CGRect)leftViewRectForBounds:(CGRect)bounds;    指定显示左附着视图的边界
 - (CGRect)rightViewRectForBounds:(CGRect)bounds;   指定显示右附着视图的边界
 
 
 
 - (void)drawTextInRect:(CGRect)rect;
 
 - (void)drawPlaceholderInRect:(CGRect)rect;
 
 通过重写这些方法，对应的一些特殊的产品设计要求基本上都能实现，这种方法的好处在于，一个产品在视觉上很多时候都是统一的。也就是说在产品开发的初期，如果重写这些方法，在后续的使用过程中，很方便的重复使用
 */


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self.beginEditingObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.endEditingObserver];
}

@end


